using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using AccountingApp.Models;

namespace AccountingApp
{
    public class SimpleDatabaseHelper
    {
        private static string dataPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");
        private static string usersFile = Path.Combine(dataPath, "users.xml");
        private static string recordsFile = Path.Combine(dataPath, "records.xml");

        static SimpleDatabaseHelper()
        {
            // 确保数据目录存在
            if (!Directory.Exists(dataPath))
            {
                Directory.CreateDirectory(dataPath);
            }
        }

        public static void InitializeDatabase()
        {
            // 如果用户文件不存在，创建空的用户列表
            if (!File.Exists(usersFile))
            {
                var users = new List<User>();
                SaveUsers(users);
            }

            // 如果记录文件不存在，创建空的记录列表
            if (!File.Exists(recordsFile))
            {
                var records = new List<AccountRecord>();
                SaveRecords(records);
            }
        }

        private static List<User> LoadUsers()
        {
            try
            {
                if (!File.Exists(usersFile))
                    return new List<User>();

                var serializer = new XmlSerializer(typeof(List<User>));
                using (var reader = new FileStream(usersFile, FileMode.Open))
                {
                    return (List<User>)serializer.Deserialize(reader);
                }
            }
            catch
            {
                return new List<User>();
            }
        }

        private static void SaveUsers(List<User> users)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(List<User>));
                using (var writer = new FileStream(usersFile, FileMode.Create))
                {
                    serializer.Serialize(writer, users);
                }
            }
            catch
            {
                // 忽略保存错误
            }
        }

        private static List<AccountRecord> LoadRecords()
        {
            try
            {
                if (!File.Exists(recordsFile))
                    return new List<AccountRecord>();

                var serializer = new XmlSerializer(typeof(List<AccountRecord>));
                using (var reader = new FileStream(recordsFile, FileMode.Open))
                {
                    return (List<AccountRecord>)serializer.Deserialize(reader);
                }
            }
            catch
            {
                return new List<AccountRecord>();
            }
        }

        private static void SaveRecords(List<AccountRecord> records)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(List<AccountRecord>));
                using (var writer = new FileStream(recordsFile, FileMode.Create))
                {
                    serializer.Serialize(writer, records);
                }
            }
            catch
            {
                // 忽略保存错误
            }
        }

        public static bool RegisterUser(User user)
        {
            try
            {
                var users = LoadUsers();

                // 检查用户名是否已存在
                if (users.Any(u => u.Username == user.Username))
                    return false;

                // 分配新的ID
                user.Id = users.Count > 0 ? users.Max(u => u.Id) + 1 : 1;
                user.CreateTime = DateTime.Now;

                users.Add(user);
                SaveUsers(users);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static User LoginUser(string username, string password)
        {
            try
            {
                var users = LoadUsers();
                return users.FirstOrDefault(u => u.Username == username && u.Password == password);
            }
            catch
            {
                return null;
            }
        }

        public static bool AddAccountRecord(AccountRecord record)
        {
            try
            {
                var records = LoadRecords();

                // 分配新的ID
                record.Id = records.Count > 0 ? records.Max(r => r.Id) + 1 : 1;
                record.RecordTime = DateTime.Now;

                records.Add(record);
                SaveRecords(records);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static List<AccountRecord> GetAccountRecords(int userId)
        {
            try
            {
                var records = LoadRecords();
                return records.Where(r => r.UserId == userId)
                             .OrderByDescending(r => r.RecordTime)
                             .ToList();
            }
            catch
            {
                return new List<AccountRecord>();
            }
        }

        public static decimal GetBalance(int userId)
        {
            try
            {
                var records = LoadRecords();
                var userRecords = records.Where(r => r.UserId == userId);

                decimal balance = 0;
                foreach (var record in userRecords)
                {
                    if (record.Type == "收入")
                        balance += record.Amount;
                    else
                        balance -= record.Amount;
                }

                return balance;
            }
            catch
            {
                return 0;
            }
        }
    }
}
